#include "StdAfx.h"
#include ".\publicfun.h"

void BSTRToUCS2(BSTR source, string &dest) {
	dest = "";
	if (source != NULL) {
		int wLen = SysStringLen(source);
		char * buffer = (char *)source;
		for(int i=0;i<wLen;i++){
			dest.append(1, buffer[2*i+1]);
			dest.append(1, buffer[2*i]);
		}
	}
}

BSTR UCS2ToBSTR(string source) {
	BSTR dest = NULL;
	size_t len = source.length();
	if (len%2==0) {
		dest = SysAllocStringLen(NULL, len/2);
		const char * buf1 = source.c_str();
		char * buffer = (char *)dest;
		for(int i=0;i<len/2;i++){
			buffer[2*i] = buf1[2*i+1];
			buffer[2*i+1] = buf1[2*i];
		}

	} else {
		dest = SysAllocStringLen(NULL, 0);
	}
	return dest;
}

void BSTRToGB18030(BSTR source, string &dest) {
	dest = "";
	if (source != NULL) {
		int wLen = SysStringLen(source);
		int aLen=WideCharToMultiByte(CP_ACP, 0, source, wLen, NULL, 0, NULL, NULL);
		char * lpa = new char[aLen];
		WideCharToMultiByte(CP_ACP, 0, source, wLen, lpa, aLen, NULL, NULL);
		dest.append(lpa, aLen);
		delete[] lpa;
	}
}

BSTR GB18030ToBSTR(string source){
	BSTR dest = NULL;
	size_t wLen = MultiByteToWideChar(CP_ACP, 0, source.c_str(), source.length(), NULL, 0);
	dest = SysAllocStringLen(NULL, wLen);
	MultiByteToWideChar(CP_ACP, 0, source.c_str(), source.length(), dest, wLen);
	return dest;
}

void UCS2ToGB18030(string source, string &dest) {
	BSTR aaa = UCS2ToBSTR(source);
	BSTRToGB18030(aaa, dest);
	SysFreeString(aaa);
}

void GB18030ToUCS2(string source, string &dest){
	BSTR aaa = GB18030ToBSTR(source);
	BSTRToUCS2(aaa, dest);
	SysFreeString(aaa);
}

void BSTRToUTF8(BSTR source, string &dest) {
	dest = "";
	if (source != NULL) {
		int wLen = SysStringLen(source);
		int aLen=WideCharToMultiByte(CP_UTF8, 0, source, wLen, NULL, 0, NULL, NULL);
		char * lpa = new char[aLen];
		WideCharToMultiByte(CP_UTF8, 0, source, wLen, lpa, aLen, NULL, NULL);
		dest.append(lpa, aLen);
		delete[] lpa;
	}
}

BSTR UTF8ToBSTR(string source){
	BSTR dest = NULL;
	size_t wLen = MultiByteToWideChar(CP_UTF8, 0, source.c_str(), source.length(), NULL, 0);
	dest = SysAllocStringLen(NULL, wLen);
	MultiByteToWideChar(CP_UTF8, 0, source.c_str(), source.length(), dest, wLen);
	return dest;
}

void GB18030ToUTF8(string source, string &dest){
	BSTR aaa = GB18030ToBSTR(source);
	BSTRToUTF8(aaa, dest);
	SysFreeString(aaa);
}

void UTF8ToGB18030(string source, string &dest){
	BSTR aaa = UTF8ToBSTR(source);
	BSTRToGB18030(aaa, dest);
	SysFreeString(aaa);
}

void toHex(string source, string &desc)
{
	desc = "";
	unsigned char a,b;
	for (unsigned int i=0;i<source.length();i++) {
		a = source[i];
		b = a >> 4;
		b = b>9?b+55:b+48;
		desc.append(1, b);
		b = a & 0xf;
		b = b>9?b+55:b+48;
		desc.append(1, b);
	}
}
